package com.xpd.spring.jdbc.dao;

import com.xpd.spring.jdbc.JdbcConfig;
import com.xpd.spring.jdbc.bean.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountDao {
    @Autowired
    JdbcTemplate jdbcTemplate;
    public void insert (Account account){
        jdbcTemplate.update("insert into bank_account values (?,?,?)",
                account.getId(),
                account.getPassword(),
                account.getBalance());
    }
    public void updateByid(Account account){
        jdbcTemplate.update("update bank_account set balance=? where id=?",
                account.getBalance(),account.getId());
    }
    public Account selectByid(int id){
        Account account = jdbcTemplate.queryForObject("select * from bank_account where id=?",
                new RowMapper<Account>() {
                    @Override
                    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Account account = new Account();
                        account.setId(rs.getInt("id"));
                        account.setPassword(rs.getString("password"));
                        account.setBalance(rs.getDouble("balance"));
                        return account;
                    }
                },id);
        return account;
    }
    public List<Account> selectAll(){
        List<Account> list = jdbcTemplate.query("select * from bank_account",
                new BeanPropertyRowMapper<Account>(Account.class));
        return  list;
    }
}
